<?php

namespace App\Http\Controllers\Admin;

use App\Models\Category;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CategoryController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->middleware('check_admin_login');
    }

    public function index()
    {
        $list = Category::query()->get();

        $plist = [];
        if(!empty($list))
        {
            foreach ($list as $v)
            {
                if($v['pid'] == 0)
                {
                    $plist[] = $v;
                }
            }
        }


        $items = [];
        if(!empty($plist))
        {
            foreach ($plist as $v)
            {
                $temp = [];
                foreach ($list as $vv)
                {
                    if($vv['pid'] == $v['id'])
                    {
                        $temp[] = [
                            'id'    => $vv['id'],
                            'title' => $vv['title'],
                            'pid'   => $vv['pid'],
                        ];
                    }
                }

                $items[] = [
                    'id'    => $v['id'],
                    'title' => $v['title'],
                    'pid'   => $v['pid'],
                    'items' => $temp
                ];
            }
        }
        return $this->ok($items);
    }

    public function parentList()
    {
        $list = Category::query()->where('pid',0)->orderBy('sort','asc')->get();

        $items = [];
        if(!empty($list))
        {
            foreach ($list as $v)
            {
                $items[] = [
                    'id' => $v->id,
                    'title' => $v->title
                ];
            }
        }
        return $this->ok($items);
    }

    /**
     * 添加分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $pid   = intval($request->get('pid'));
        $sort  = intval($request->get('sort'));
        $title = trim($request->get('title'));

        if(empty($pid) || empty($title))
        {
            return $this->err(1,200,'','参数错误');
        }

        $insert_id = Category::query()->insertGetId([
            'pid'        => $pid,
            'title'      => $title,
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]);

        if($insert_id)
        {
            if($sort)
            {
                Category::query()->where('id',$insert_id)->update([
                    'sort' => $sort
                ]);
            }
            else
            {
                Category::query()->where('id',$insert_id)->update([
                    'sort' => $insert_id
                ]);
            }

            return $this->ok([],'添加成功');
        }
        return $this->err(1,200,'','添加失败');
    }

    /**
     * 修改分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request)
    {
        $id    = intval($request->get('id'));
        $pid   = intval($request->get('pid'));
        $title = trim($request->get('title'));
        $sort  = intval($request->get('sort'));

        if(empty($id) || empty($pid) || empty($title))
        {
            return $this->err(1,200,'','参数错误');
        }

        $category = Category::find($id);
        if(empty($category))
        {
            return $this->err(1,200,'','分类不存在');
        }

        $category->update([
            'pid'   => $pid,
            'title' => $title,
            'sort'  => $sort,
        ]);
        return $this->ok([],'修改成功');
    }

    public function destroy(Request $request)
    {
        $id = intval($request->get('id'));

        if(!$id)
        {
            return $this->err(1,200,'','参数错误');
        }

        $category = Category::find($id);
        if(empty($category))
        {
            return $this->err(1,200,'','分类不存在');
        }
        $category->delete();
        if($category->trashed())
        {
            return $this->ok([],'删除成功');
        }
        return $this->err(1,200,'','删除失败');
    }

    public function categories(Request $request)
    {
        $pid = intval($request->get('pid'));  //一级分类id
        if(empty($pid))
        {
            return $this->err(1,200,'','参数错误');
        }


        $items = [['id' => 0,'title' => '请选择', 'sort' => 0,'count' => 0]];
        $list = Category::query()->select(['id','title','sort'])->where('pid',$pid)->orderBy('sort','asc')->get();
        if(!empty($list))
        {
            foreach ($list as $v)
            {
                $count = DB::table('book_category_relations')->where('category_id',$v->id)->count();

                $items[] = [
                    'id'    => $v->id,
                    'title' => $v->title,
                    'sort'  => $v->sort,
                    'count' => $count,
                ];
            }
        }

        return $this->ok($items);
    }
}
